//
//  WBOAuthViewController.swift
//  simpleWeibo
//
//  Created by 孙林 on 2018/6/10.
//  Copyright © 2018年 孙林. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        //设置代理
        webView.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: false)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        //1 url确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        //2建立请求
        let request = URLRequest(url: url)
        //3加载请求
        webView.loadRequest(request)
    }
    
    // MARK: - 监听方法
    @objc fileprivate func close () {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '335089101@qq.com';" + "document.getElementById('passwd').value = 'sunlin86595981ab';"
        //让webView执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }

}


extension WBOAuthViewController: UIWebViewDelegate {
    
    /// webView 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        print("加载请求---\(String(describing: request.url?.absoluteString))")
        
        //思路
        //1如果请求地址包含 http://baidu.com 不加载页面/ 否则加载页面
        //request.url?.absoluteString.hasPrefix(WBRedirectURI) 返回的是可选项  true/false/nil
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true
        }
        
        //2从 http://baidu.com 回调地址的 '查询字符串'中查找 'code='
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        //3从query 字符串中取出 授权码
        //代码走到这里 一定包含 授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码- \(code)")
        
        //4试用授权码获取 AccessToken
        WBNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录失败")
            } else {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                // 跳转界面
                NotificationCenter.default.post(name: NSNotification.Name(WBUserLoginSuccessNotification), object: nil)
                
                //关闭 当前界面
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
}
